package com.example.browser;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;

import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.browser.zxing.android.CaptureActivity;
import com.example.geturl.web.SniffingUtil;
import com.google.zxing.common.StringUtils;

import org.jsoup.internal.StringUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends BaseActivity1 {
    private RelativeLayout myView;
    private ImageView home_search,bk,his,list_home;

    private TextView home_edit;
    //二维码 https://www.cnblogs.com/xch-yang/p/9418493.html
    private ImageView home_qr;
    private static final int REQUEST_CODE_SCAN = 12;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
//退出程序
    private long mExitTime;  //存在时间，初值为0，用于和当前时间（毫秒数）做差值

    //默认百度搜索
    private String surl="https://www.baidu.com/s?wd=";
    private LinearLayout sb;


    private int list_count=0;





    private Boolean isUser=true;
    String androidId;
    String htmlString;
    private String list_back=null,clip=null;
    //在activity关闭另外一个activity http://blog.sina.com.cn/s/blog_6e334dc701018m2v.html
    public static MainActivity instance = null;
// SharedPreferences数据存储
    private static final String FILENAME="YX";
    private  SharedPreferences share;

    private static final int CHOOSE=0;
    private final String IMAGE_TYPE="image/*";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//去掉标题栏注意这句一定要写在setContentView()方法的前面，不然会报错的
        setContentView(R.layout.home);
        home_search=(ImageView) findViewById(R.id.home_search);
        home_edit=(TextView) findViewById(R.id.home_edit);
        myView=(RelativeLayout)findViewById(R.id.myView);
        list_home = (ImageView) findViewById(R.id.list_home);

        sb = (LinearLayout) findViewById(R.id.sb);
        bk=(ImageView)findViewById(R.id.bk) ;
        his =(ImageView) findViewById(R.id.his);


//在activity关闭另外一个activity http://blog.sina.com.cn/s/blog_6e334dc701018m2v.html
        instance = this;
        home_qr =(ImageView) findViewById(R.id.home_qr);
        try {
            if(!getPackageManager().getPackageInfo(getPackageName(),0).packageName.equals("com.zjyzhj.dmbrowser")){
                finish();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        initViews();
        if (!checkConnectNetwork(MainActivity.this)) {
            new Handler(MainActivity.this.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "请连接网络进来", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
            return;
        }
        // Toast.makeText(MainActivity.this,isUser, Toast.LENGTH_SHORT).show();
        //网络属于耗时操作 需要多线程来运行 否则会异常
        //new Tip().execute();
        /*androidId = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        new Thread(new Runnable(){
            public void run(){
                //获取服务端的url
                try {
                   htmlString=CodeHtml.GetHtml("", "utf-8");
                    //System.out.println("a啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊"+htmlString);
                     if(htmlString!=null){
                         isUser= htmlString.contains(androidId)||htmlString.contains(DeviceIdUtils.getDeviceId(getApplicationContext()));
                     }
                }catch(Exception e){
                    Toast.makeText(MainActivity.this, "服务器错误或者网络出问题", Toast.LENGTH_SHORT).show();

                }
            }
        }).start();*/

        zbpd();




    }
    //判断是否联网 https://blog.csdn.net/baidu_38995168/article/details/107413163
    private boolean checkConnectNetwork(Context context) {

        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo net = conn.getActiveNetworkInfo();
        if (net != null && net.isConnected()) {
            return true;
        }
        return false;
    }


    private void appG(String appTxt) {
        Dialog dialog = new AlertDialog.Builder(MainActivity.this)	// 创建Dialog
                .setIcon(R.drawable.iconyx)	// 设置显示图片
                .setTitle("公告")		// 设置标题
                .setMessage(appTxt)	// 设置组件
                .setCancelable(false)
                .create();// 创建对话框
        dialog.show();		// 显示对话框


    }
    private void zbpd(){
        if(installed(this,"app.greyshirts.sslcapture")||installed(this,"com.example.logcat")||
                installed(this,"com.lml.flywindow")||installed(this,"blake.hamilton.bitshark")||
                installed(this,"su.sniff.cepter")||installed(this,"com.evbadroid.wicap")||
                installed(this,"com.guoshi.httpcanary")||installed(this,"com.minhui.networkcapture")
                ||installed(this,"com.minhui.networkcapture.pro")){
            Toast.makeText(this, "请卸载抓包软件再使用", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    public static boolean installed(Context context, String appPackageName) {
        PackageManager packageManager =context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        for (PackageInfo pkif : pinfo) {
            String pn = pkif.packageName;
            if (appPackageName.equals(pn)) {
                return true;
            }
        }
        return false;
    }

    private void initViews() {
        //需要权限
        String[] PERMISSIONS = {
                "android.permission.READ_EXTERNAL_STORAGE",
                "android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"};
//检测是否有写的权限
        int permission = ContextCompat.checkSelfPermission(MainActivity.this,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 2);
        }else {
            fileIsExists();
            String root = Environment.getExternalStorageDirectory().getAbsolutePath();
            String newPath="/dmbrowser/downloadpic";
            String sharePath="/dmbrowser/sharepic";
            String qrPath="/dmbrowser/qrpic";
            File f = new File(root,newPath);
            File share = new File(root,sharePath);
            File qr = new File(root,qrPath);
            if (!f.exists()) {
                f.mkdirs();
            }
            if (!qr.exists()) {
                qr.mkdirs();
            }
            if (!share.exists()) {
                share.mkdirs();
            }
        }

        // SharedPreferences数据存储
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
//默认百度搜索
        String searchhistory = share.getString("searchurl", "https://www.baidu.com/s?wd=");

        if(searchhistory.equals("https://www.baidu.com/s?wd=")){
            MainActivity.this.home_search.setImageResource(R.drawable.baidu);
            surl="https://www.baidu.com/s?wd=";
        }else if(searchhistory.equals("https://www.sogou.com/web?query=")){
            MainActivity.this.home_search.setImageResource(R.drawable.sougou);
            surl="https://www.sogou.com/web?query=";
        }else if(searchhistory.equals("http://www.google.com.tw/search?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.chrome);
            surl="http://www.google.com.tw/search?q=";
        }else if(searchhistory.equals("http://cn.bing.com/search?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.bing);
            surl="http://cn.bing.com/search?q=";
        }else if(searchhistory.equals("https://quark.sm.cn/s?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.quak);
            surl="http://cn.bing.com/search?q=";
        }else {
            home_search.setImageResource(R.drawable.iconyx);
        }


        bk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this, bookmark.class);
                startActivity(intent);
            }
        });
        list_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor edit=share.edit();
                //弹出对话框
                final Dialog dialog = new Dialog(MainActivity.this, R.style.MyDialogActivityStyle);
                View list_view = View.inflate(MainActivity.this, R.layout.activity_list3, null);
                dialog.setContentView(list_view);
                dialog.setCanceledOnTouchOutside(true);
                Window window = dialog.getWindow();//得到对话框的窗口．
                WindowManager.LayoutParams wl = window.getAttributes();

                //https://snakey.blog.csdn.net/article/details/53693446?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link
                // 将对话框的大小按屏幕大小的百分比设置

                WindowManager windowManager = getWindowManager();
                Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
                wl.width = (int)(display.getWidth() * 1); //设置宽度
                wl.height = (int)(display.getHeight() * 0.4);
                wl.alpha = 1f;// 设置对话框的透明度,1f不透明
                window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
                window.setAttributes(wl);


                TextView nighttxt=list_view.findViewById(R.id.nighttxt);
                LinearLayout list_b=list_view.findViewById(R.id.list_b);
                if (share.getString("night", "夜间模式关闭").equals("夜间模式关闭")){
                    nighttxt.setText("夜间模式");
                    list_b.setBackgroundResource(R.drawable.view);

                }else {
                    nighttxt.setText("日间模式");
                    list_b.setBackgroundResource(R.drawable.night_view);
                }

                dialog.show();

            }
        });
his.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent=new Intent();
        intent.setClass(MainActivity.this,history.class);
        startActivity(intent);
    }
});
        //打开本地图库
        myView.setOnLongClickListener(new android.view.View.OnLongClickListener(){
//            MyDialog myDialog = new MyDialog(MainActivity.this,"我是自定义的Disalog");
            @Override
            public boolean onLongClick(android.view.View v){
                String[] PERMISSIONS = {
                        "android.permission.READ_EXTERNAL_STORAGE",
                        "android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"};
//检测是否有写的权限
                int permission = ContextCompat.checkSelfPermission(MainActivity.this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS,1);
                }else {
                    Intent intent_choose=new Intent(Intent.ACTION_PICK);//Intent.ACTION_GET_CONTENT和是获得最近使用过的图片。
                    intent_choose.setType(IMAGE_TYPE);//应该是指定数据类型是图片。
                    startActivityForResult(intent_choose,CHOOSE);
                }


////对话框显示
//                myDialog.show();

                return false;
            }
        });

        home_qr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //动态权限申请
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    //扫码
                    goScan();
                }
            }
        });


//浮窗布局,传递数据
        home_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,MainActivity2.class);
                startActivityForResult(intent,2);

            }
        });

        home_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this,Main4Activity.class);
                intent.putExtra("searchpic",surl);
                startActivityForResult(intent,3);



            }
        });





    }



    //https://blog.csdn.net/MacaoPark/article/details/116034812
    private void clearCacheX() {
        File file = getCacheDir().getAbsoluteFile();//删除缓存
        deleteFile(file);
        Toast.makeText(this, "清理成功", Toast.LENGTH_SHORT).show();
    }

    public void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        }
    }

    private void goScan(){
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    //获取返回搜索url
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 2:
                SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
//默认百度搜索
                String searchhistory = share.getString("searchurl", "https://www.baidu.com/s?wd=");
                if(searchhistory.equals("https://www.baidu.com/s?wd=")){
                    MainActivity.this.home_search.setImageResource(R.drawable.baidu);

                }else if(searchhistory.equals("https://www.sogou.com/web?query=")){
                    MainActivity.this.home_search.setImageResource(R.drawable.sougou);

                }else if(searchhistory.equals("http://www.google.com.tw/search?q=")){
                    MainActivity.this.home_search.setImageResource(R.drawable.chrome);

                }else if(searchhistory.equals("http://cn.bing.com/search?q=")){
                    MainActivity.this.home_search.setImageResource(R.drawable.bing);

                }else if(searchhistory.equals("https://quark.sm.cn/s?q=")){
                    MainActivity.this.home_search.setImageResource(R.drawable.quak);

                }
                break;
            case CHOOSE:
                if(resultCode==RESULT_OK){
                   // https://blog.csdn.net/bigtree_mfc/article/details/55049501?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_default&utm_relevant_index=5
                    Uri selectedImage = data.getData();//返回的是uri
                    DisplayMetrics displayMetrics = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                    int displayheight = displayMetrics.heightPixels;//高度
                    int displayWidth = displayMetrics.widthPixels;//宽度


                    String [] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String path = cursor.getString(columnIndex);
                    copyFile(path);
                   // Bitmap bitmap = BitmapFactory.decodeFile(path);
                    //saveBitmap(decodeUri(MainActivity.this,selectedImage,displayWidth,displayheight));
                    Drawable drawable =new BitmapDrawable(decodeUri(MainActivity.this,selectedImage,displayWidth,displayheight));
                    myView.setBackground(drawable);
                }
                break;
            case REQUEST_CODE_SCAN:
                if (resultCode == RESULT_OK) {//二维码 https://www.cnblogs.com/xch-yang/p/9418493.html
                    if (data != null) {
                        //返回的文本内容
                        String content = data.getStringExtra(DECODED_CONTENT_KEY);
                        Intent it = new Intent(MainActivity.this, webview.class);
                        //传递搜索框内容
                        it.putExtra("searchText",content);
//获取搜素引擎返回的数据再传递
                        startActivity(it);
                        //返回的BitMap图像
                        Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                    }
                    break;
                }



        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //扫码
                    goScan();
                } else {
                    Toast.makeText(this, "你拒绝了权限申请，无法打开相机扫码哟！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    //https://blog.csdn.net/u013642500/article/details/80067680?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164291408116780264065119%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=164291408116780264065119&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-1-80067680.pc_search_result_control_group&utm_term=android%E7%AE%80%E5%8D%95%E5%AE%9E%E7%8E%B0%E6%8B%B7%E8%B4%9D%E6%96%87%E4%BB%B6%E5%88%B0%E6%8C%87%E5%AE%9A%E6%96%87%E4%BB%B6%E5%A4%B9&spm=1018.2226.3001.4187
    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
    // * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath) {
        //需要权限
        String[] PERMISSIONS = {
                "android.permission.READ_EXTERNAL_STORAGE",
                "android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"};
//检测是否有写的权限
        int permission = ContextCompat.checkSelfPermission(MainActivity.this,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 1);
        }

        try {
            String newPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/dmbrowser/backpic/background.jpg";
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ( (byteread = inStream.read(buffer)) != -1) {
                   // bytesum += byteread; //字节数 文件大小
                    //System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }

                inStream.close();
                fs.flush();
                fs.close();
            }
        }
        catch (Exception e) {
            Toast.makeText(MainActivity.this, "设置失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();

        }

    }
    //判断文件是否存在
    private void fileIsExists() {

            try {
                String root = Environment.getExternalStorageDirectory().getAbsolutePath();
                String dirName = "dmbrowser/backpic";
                String downPic = "dmbrowser/downloadpic";
                String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/dmbrowser/backpic/background.jpg";
                File appDir = new File(root, dirName);
                File down = new File(root,downPic);
                File f = new File(newPath);
                if(share.getString("night", "夜间模式关闭").equals("夜间模式关闭")){
                    if (!appDir.exists()&&!down.exists()) {

                        appDir.mkdirs();
                        down.mkdirs();
                        myView.setBackgroundResource(R.drawable.backg);
                        sb.setBackgroundResource(R.drawable.searchview);
                    }else if(appDir.exists()&&!down.exists()){
                        down.mkdirs();
                    } else if(!appDir.exists()&&down.exists()){
                        appDir.mkdirs();
                        myView.setBackgroundResource(R.drawable.backg);
                        sb.setBackgroundResource(R.drawable.searchview);
                    }else if (appDir.exists() && !f.exists()) {
                        myView.setBackgroundResource(R.drawable.backg);
                        sb.setBackgroundResource(R.drawable.searchview);
                    } else if (appDir.exists() && f.exists()) {


                        // https://blog.csdn.net/bigtree_mfc/article/details/55049501?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_default&utm_relevant_index=5
                        Bitmap bitmap = BitmapFactory.decodeFile(newPath);
                        Drawable drawable = new BitmapDrawable(bitmap);
                        myView.setBackground(drawable);
                        sb.setBackgroundResource(R.drawable.searchview);
                    }else {
                        myView.setBackgroundResource(R.drawable.backg);
                        sb.setBackgroundResource(R.drawable.searchview);
                    }
                }else {
                    myView.setBackgroundColor(Color.rgb(105,105,105));
                    sb.setBackgroundResource(R.drawable.night_search);
                }


            } catch (Exception e) {

            }


    }



    //https://www.cnblogs.com/itlgl/p/10419278.html
    //http://blog.sina.com.cn/s/blog_5de73d0b0100zfm8.html
    /**
     * 读取一个缩放后的图片，限定图片大小，避免OOM
     * @param uri       图片uri，支持“file://”、“content://”
     * @param maxWidth  最大允许宽度
     * @param maxHeight 最大允许高度
     * @return  返回一个缩放后的Bitmap，失败则返回null
     */
    public static Bitmap decodeUri(Context context, Uri uri, int maxWidth, int maxHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; //只读取图片尺寸
        resolveUri(context, uri, options);

        //计算实际缩放比例
        int scale = 1;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            if ((options.outWidth / scale > maxWidth &&
                    options.outWidth / scale > maxWidth * 1.4) ||
                    (options.outHeight / scale > maxHeight &&
                            options.outHeight / scale > maxHeight * 1.4)) {
                scale++;
            } else {
                break;
            }
        }

        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;//读取图片内容
        options.inPreferredConfig = Bitmap.Config.RGB_565; //根据情况进行修改
        Bitmap bitmap = null;
        try {
            bitmap = resolveUriForBitmap(context, uri, options);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    private static void resolveUri(Context context, Uri uri, BitmapFactory.Options options) {
        if (uri == null) {
            return;
        }

        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
                ContentResolver.SCHEME_FILE.equals(scheme)) {
            InputStream stream = null;
            try {
                stream = context.getContentResolver().openInputStream(uri);
                BitmapFactory.decodeStream(stream, null, options);
            } catch (Exception e) {
                Log.w("resolveUri", "Unable to open content: " + uri, e);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        Log.w("resolveUri", "Unable to close content: " + uri, e);
                    }
                }
            }
        } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            Log.w("resolveUri", "Unable to close content: " + uri);
        } else {
            Log.w("resolveUri", "Unable to close content: " + uri);
        }
    }

    private static Bitmap resolveUriForBitmap(Context context, Uri uri, BitmapFactory.Options options) {
        if (uri == null) {
            return null;
        }

        Bitmap bitmap = null;
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
                ContentResolver.SCHEME_FILE.equals(scheme)) {
            InputStream stream = null;
            try {
                stream = context.getContentResolver().openInputStream(uri);
                bitmap = BitmapFactory.decodeStream(stream, null, options);
            } catch (Exception e) {
                Log.w("resolveUriForBitmap", "Unable to open content: " + uri, e);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        Log.w("resolveUriForBitmap", "Unable to close content: " + uri, e);
                    }
                }
            }
        } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            Log.w("resolveUriForBitmap", "Unable to close content: " + uri);
        } else {
            Log.w("resolveUriForBitmap", "Unable to close content: " + uri);
        }

        return bitmap;
    }



//退出程序提示
    @Override
         public boolean onKeyDown(int keyCode, KeyEvent event) {
                         if (keyCode == KeyEvent.KEYCODE_BACK) {
                                     if ((System.currentTimeMillis() - mExitTime) > 2000) {  //mExitTime的初始值为0，currentTimeMillis()肯定大于2000（毫秒），所以第一次按返回键的时候一定会进入此判断
                                                 Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                                                mExitTime = System.currentTimeMillis();

                                        } else {
                                         exit();
                                     }
                                    return true;
                           }
                       return super.onKeyDown(keyCode, event);
               }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    //有弹窗点击阴影部分时
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        //背景以及文件夹初始化
        fileIsExists();

    }
    @Override
    protected void onResume() {
        super.onResume();
        fileIsExists();
        //默认百度搜索
        String searchhistory = share.getString("searchurl", "https://www.baidu.com/s?wd=");
        if(searchhistory.equals("https://www.baidu.com/s?wd=")){
            MainActivity.this.home_search.setImageResource(R.drawable.baidu);

        }else if(searchhistory.equals("https://www.sogou.com/web?query=")){
            MainActivity.this.home_search.setImageResource(R.drawable.sougou);

        }else if(searchhistory.equals("http://www.google.com.tw/search?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.chrome);

        }else if(searchhistory.equals("http://cn.bing.com/search?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.bing);

        }else if(searchhistory.equals("https://quark.sm.cn/s?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.quak);
        }else {
            MainActivity.this.home_search.setImageResource(R.drawable.iconyx);
        }


    }
    @Override
    protected void onRestart() {
        super.onRestart();
        fileIsExists();
        if(share.getString("night", "夜间模式关闭").equals("夜间模式关闭")){

        }else {
            myView.setBackgroundColor(Color.rgb(105,105,105));
        }
//默认百度搜索
        String searchhistory = share.getString("searchurl", "https://www.baidu.com/s?wd=");
        if(searchhistory.equals("https://www.baidu.com/s?wd=")){
            MainActivity.this.home_search.setImageResource(R.drawable.baidu);

        }else if(searchhistory.equals("https://www.sogou.com/web?query=")){
            MainActivity.this.home_search.setImageResource(R.drawable.sougou);

        }else if(searchhistory.equals("http://www.google.com.tw/search?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.chrome);

        }else if(searchhistory.equals("http://cn.bing.com/search?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.bing);

        }else if(searchhistory.equals("https://quark.sm.cn/s?q=")){
            MainActivity.this.home_search.setImageResource(R.drawable.quak);
        }else {
            home_search.setImageResource(R.drawable.iconyx);
        }
    }
    //https://blog.csdn.net/weixin_43873198/article/details/109489332
/*    class Tip extends AsyncTask<Void,Void,String> {
        String htmlString="【公告】获取公告异常，获取网络错误/服务器异常【公告】【推广】暂无分享【推广】【软件开放】软件关闭【软件开放】【原因】暂无【原因】";

        @Override
        protected String doInBackground(Void... voids) {  //耗时操作代码在后台进行

            try {
                 htmlString=CodeHtml.GetHtml("", "utf-8");

            }catch(Exception e){
                Toast.makeText(MainActivity.this, "服务器错误或者无网络连接", Toast.LENGTH_SHORT).show();

            }
            return htmlString;
        }
        @Override
        protected void onPostExecute(String htmlString) {  //在后台数据提交后更新UI主线程
            if (htmlString != "【公告】获取公告异常，获取网络错误/服务器异常【公告】【推广】暂无分享【推广】【软件开放】软件关闭【软件开放】【原因】暂无【原因】"){
                String[]  upstrs=new String[1000];
                upstrs=htmlString.split("【公告】");
                String[]  upUrl=new String[1000];
                upUrl=htmlString.split("【推广】");
                String[]  appIf=new String[1000];
                appIf=htmlString.split("【软件开放】");
                String[]  appTxt=new String[1000];
                appTxt=htmlString.split("【原因】");

                    if("软件关闭".equals(appIf[1])){
                        appG(appTxt[1]);
                        upApp(upstrs[1].toString(),upUrl[1].toString());
                    }

            }
            else{
                Toast.makeText(getApplicationContext(), "请查看网络并退出重新进入", Toast.LENGTH_SHORT).show();
                finish();
            }

        }
    }*/
}
